<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="主线路" prop="mainRouteId">
        <el-select clearable filterable v-model="queryParams.mainRouteId" @keyup.enter="handleQuery" placeholder="请选择主线路">
          <el-option v-for="item in dictTagHostRoutes" :key="item.value" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-tree-select v-model="queryParams.deptId" @keyup.enter="handleQuery" :data="deptOptions"
          :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门" check-strictly
          clearable filterable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['basic:route:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['basic:route:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['basic:route:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport"
          v-hasPermi="['basic:route:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['basic:route:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleRouteStationImport"
          v-hasPermi="['basic:routeStation:import']">线路站点导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="routeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column label="编号" align="left" prop="code" />
      <el-table-column label="名称" align="left" prop="name">
        <template #default="scope">
          <el-tag>{{ scope.row.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="设备线路" align="left" prop="deviceRouteCode" />
      <el-table-column label="线路运行方式" align="center" prop="operationMode">
        <template #default="scope">
          <span>{{ scope.row.operationMode == 1 ? '环线' : '上下行' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_data_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="地区" align="left" prop="areaName" />
      <el-table-column label="线路复合类型" align="center" prop="compoundType">
        <template #default="scope">
          <span>{{ scope.row.compoundType == '1' ? '主线路' : '从线路' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="主线路" align="left" prop="mainRouteId">
        <template #default="scope">
          <dict-tag :options="dictTagHostRoutes" :value="scope.row.mainRouteId" v-if="scope.row.compoundType == '2'" />
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="部门" align="left" prop="deptName">
        <template #default="scope">
          <el-tag type="info">{{ scope.row.deptName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['basic:route:edit']">修改</el-button>
          <el-dropdown trigger="click" type="primary">
            <span class="el-dropdown-link" style="font-size: 13px">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="$auth.hasPermi('basic:routeStation:list')">
                  <el-button link type="primary" size="small" icon="Edit"
                    @click="routeStationList(scope.row)">站点管理</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="$auth.hasPermi('basic:routeRegion:list')">
                  <el-button link type="primary" size="small" icon="Edit"
                    @click="routeRegionList(scope.row)">场区管理</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="$auth.hasPermi('dispatch:schedulingPlanTimetable:list') && scope.row.compoundType == 1">
                  <el-button link type="primary" size="small" icon="List"
                    @click="routeVehicleList(scope.row)">车辆管理</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="$auth.hasPermi('dispatch:routeStationAssess:query')">
                  <el-button link type="primary" size="small" icon="List"
                    @click="routeStationsConfigList(scope.row)">站点考核配置</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="$auth.hasPermi('dispatch:routeStationExtend:query')">
                  <el-button link type="primary" size="small" icon="List"
                    @click="routeConfigList(scope.row)">扩展配置</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="$auth.hasPermi('dispatch:routeManHour:edit')">
                  <el-button link type="primary" size="small" icon="List"
                    @click="routeManHourList(scope.row)">司机工作时长</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="$auth.hasPermi('basic:route:remove')">
                  <el-button link type="danger" size="small" icon="Delete"
                    @click="handleDelete(scope.row)">删除</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改线路对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="routeRef" :model="form" :rules="rules" label-width="165px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="编号" prop="code">
              <el-input v-model="form.code" placeholder="请输入编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备线路" prop="deviceRouteCode">
              <el-input v-model="form.deviceRouteCode" placeholder="请输入设备线路" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select filterable v-model="form.status" placeholder="请选择状态">
                <el-option v-for="dict in sys_data_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地区" prop="areaId">
              <el-cascader v-model="form.areaId" :options="areaOptions"
                :props="{ value: 'id', label: 'label', children: 'children', emitPath: false }" placeholder="请选择地区"
                filterable :show-all-levels="false" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <el-tree-select v-model="form.deptId" :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门"
                check-strictly filterable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="线路复合类型" prop="compoundType">
              <el-select filterable v-model="form.compoundType" placeholder="请选择线路复合类型">
                <el-option v-for="item in compoundTypeOptions" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="线路运行方式" prop="operationMode">
              <el-select filterable v-model="form.operationMode" placeholder="请选择线路运行方式">
                <el-option v-for="item in routeModeOptions" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.compoundType == '2'">
            <el-form-item label="主线路" prop="mainRouteId">
              <el-select clearable filterable v-model="form.mainRouteId" placeholder="请选择主线路">
                <el-option v-for="item in hostRouteOptions" :key="item.id" :label="item.name"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上行首班时间" prop="upFirstTime">
              <el-time-select clearable v-model="form.upFirstTime" :start="timePickerStart" :end="timePickerEnd"
                :step="timePickerStep" placeholder="请选择上行首班时间">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下行首班时间" prop="downFirstTime">
              <el-time-select clearable v-model="form.downFirstTime" :start="timePickerStart" :end="timePickerEnd"
                :step="timePickerStep" placeholder="请选择下行首班时间">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上行末班时间" prop="upLastTime">
              <el-time-select clearable v-model="form.upLastTime" :start="timePickerStart" :end="timePickerEnd"
                :step="timePickerStep" placeholder="请选择上行末班时间">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下行末班时间" prop="downLastTime">
              <el-time-select clearable v-model="form.downLastTime" :start="timePickerStart" :end="timePickerEnd"
                :step="timePickerStep" placeholder="请选择下行末班时间">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上行单次运行时间" prop="upDrivingTime">
              <el-input v-model="form.upDrivingTime" placeholder="请输入上行单次运行时间 / 分钟" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下行单次运行时间" prop="downDrivingTime">
              <el-input v-model="form.downDrivingTime" placeholder="请输入下行单次运行时间 / 分钟" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog align-center :title="upload.title" v-model="upload.open" width="400px">
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls"  action="#" :http-request="httpRequest"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag :data="upload.form">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <el-form :model="upload.form" ref="uploadForm" label-width="100px">
              <el-form-item label="部门" :rules="{ required: true, message: '部门不能为空', trigger: 'change' }" prop="deptId">
                <el-tree-select v-model="upload.form.deptId" :data="deptOptions"
                  :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门"
                  check-strictly filterable />
              </el-form-item>
              <el-form-item label="地区" prop="areaId" :rules="{ required: true, message: '请选择地区', trigger: 'change' }">
                <el-cascader v-model="upload.form.areaId" :options="areaOptions"
                  :props="{ value: 'id', label: 'label', children: 'children', emitPath: false }" placeholder="请选择地区"
                  filterable :show-all-levels="false" />
              </el-form-item>
              <div class="el-upload__tip">
                <el-checkbox v-model="upload.form.updateSupport" label="是否更新已经存在的数据" />
              </div>
            </el-form>
            <br />
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 线路站点导入 -->
    <el-dialog :title="uploadStation.title" v-model="uploadStation.open" width="600px" append-to-body>
      <el-upload ref="routeStationRef" :limit="1" accept=".xlsx, .xls" action="#" :http-request="httpStationRequest" :disabled="uploadStation.isUploading"
        :on-progress="handleRouteStationFileUploadProgress" :on-success="handleRouteStationFileSuccess"
        :auto-upload="false" drag :data="uploadStation.form">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <el-form :model="uploadStation.form" ref="routeStationForm" label-width="220px">
              <el-form-item label="线路所属机构" :rules="{ required: true, message: '线路所属机构不能为空', trigger: 'change' }">
                <el-tree-select v-model="uploadStation.form.deptId" :data="deptOptions"
                  :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择线路所属机构"
                  check-strictly filterable />
              </el-form-item>
              <el-form-item label="站点所属地区" prop="areaId" :rules="{ required: true, message: '请选择站点所属地区', trigger: 'change' }">
                <el-cascader v-model="uploadStation.form.areaId" :options="areaOptions"
                  :props="{ value: 'id', label: 'label', children: 'children', emitPath: false }" placeholder="请选择站点所属地区"
                  filterable :show-all-levels="false" />
              </el-form-item>
              <el-form-item label="坐标类型" prop="type" :rules="{ required: true, message: '请选择类型', trigger: 'change' }">
                <el-select filterable v-model="uploadStation.form.type" placeholder="请选择坐标类型">
                  <el-option v-for="dict in sys_gps_coordinate" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="站点半径覆盖范围" :rules="{ required: true, message: '半径覆盖范围不能为空', trigger: 'blur' }">
                <el-input-number v-model="uploadStation.form.stationRadius" :min="0" label="描述文字"></el-input-number>
              </el-form-item>
              <el-form-item label="站点方位角偏移范围（正向）" :rules="{ required: true, message: '方位角正向不能为空', trigger: 'blur' }">
                <el-input-number v-model="uploadStation.form.positiveAngle" :min="0" label="正向"></el-input-number>
              </el-form-item>
              <el-form-item label="站点方位角偏移范围（反向）" :rules="{ required: true, message: '方位角反向不能为空', trigger: 'blur' }">
                <el-input-number v-model="uploadStation.form.reverseAngle" :min="0" label="反向"></el-input-number>
              </el-form-item>
              <el-form-item label="是否全局更新数据">
                <el-radio-group v-model="uploadStation.form.updateScope">
                  <el-radio key="1" label="1">部分更新</el-radio>
                  <el-radio key="2" label="2">全部更新</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
            <br />
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importRouteStationTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitRouteStationFileForm">确 定</el-button>
          <el-button @click="uploadStation.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="manageTitle" v-model="manageOpen" :width="manageType == 'routeStation' ? '80%' : '800px'"
      append-to-body>
      <routeStation :route-id="routeId" v-if="manageType == 'routeStation'" />
      <routeRegion :route-id="routeId" v-if="manageType == 'routeRegion'" />
      <routeVehicle :route-id="routeId" :dept-id="deptId" v-if="manageType == 'routeVehicle'" />
      <routeConfig :route-id="routeId" v-if="manageType == 'routeConfig'" />
      <routeStationExtend :route-id="routeId" v-if="manageType == 'routeStationsConfig'" />
      <routeManHour :route-id="routeId" @cancel="() => { manageOpen = false }" v-if="manageType == 'routeManHour'" />
    </el-dialog>
  </div>
</template>

<script setup name="Route">
import { getToken } from "@/utils/auth"
import { listRoute, getRoute, delRoute, addRoute, updateRoute } from "@/api/basic/route";
import { deptTreeSelect } from "@/api/system/user";
import { areaTreeSelect } from "@/api/basic/area";
const { proxy } = getCurrentInstance();
const { sys_data_status, sys_gps_coordinate } = proxy.useDict('sys_data_status', 'sys_gps_coordinate');

const routeList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const timePickerStart = '04:30';
const timePickerEnd = '23:30';
const timePickerStep = '00:15';
const routeModeOptions = [{
  value: '1',
  label: '环线'
}, {
  value: '2',
  label: '上下行'
}]
const compoundTypeOptions = [{
  value: '1',
  label: '主线路'
}, {
  value: '2',
  label: '从线路'
}]
const hostRouteOptions = ref([])
const dictTagHostRoutes = ref([])
const deptOptions = ref([])
const areaOptions = ref([])

/** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  form: {
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    deptId: undefined,
    compoundType: '1',
    areaId: null,
  },
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url:  "basic/route/import/data"
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: undefined,
    name: undefined,
    mainRouteId: undefined,
    deptId: undefined,
  },
  rules: {
    code: [
      { required: true, message: "编号不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    deviceRouteCode: [
      { required: true, message: "设备线路不能为空", trigger: "blur" }
    ],
    operationMode: [
      { required: true, message: "线路运行方式不能为空", trigger: "change" }
    ],
    compoundType: [
      { required: true, message: "线路复合类型", trigger: "change" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    deptId: [
      { required: true, message: "部门不能为空", trigger: "change" }
    ],
    areaId: [
      { required: true, message: "地区不能为空", trigger: "change" }
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};

/** 查询地区下拉树结构 */
function getAreaTree() {
  areaTreeSelect().then(response => {
    areaOptions.value = response.data;
  })
}

/** 查询主线路下拉选择结构 */
function getHostRoute() {
  hostRouteOptions.value = [];
  dictTagHostRoutes.value = [];

  let query = {
    compoundType: '1',
    pageSize: 9999
  }
  listRoute(query).then(response => {
    response.rows.forEach(item => {
      //正常状态的主线路
      if (item.status == 0) {
        hostRouteOptions.value.push(item)
      }
      dictTagHostRoutes.value.push({
        value: item.id,
        label: item.name,
        elTagType: 'danger'
      })
    })
  })
}

/** 查询线路列表 */
function getList() {
  loading.value = true;
  listRoute(queryParams.value).then(response => {
    routeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    code: null,
    name: null,
    deviceRouteCode: null,
    operationMode: '2',
    upFirstTime: null,
    upLastTime: null,
    upDrivingTime: null,
    downFirstTime: null,
    downLastTime: null,
    downDrivingTime: null,
    compoundType: '1',
    mainRouteId: null,
    status: '0',
    deptId: deptOptions.value[0].id,
    areaId: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateTime: null,
    updateBy: null
  };
  proxy.resetForm("routeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加线路";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getRoute(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改线路";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["routeRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.compoundType == '1') {
        form.value.mainRouteId = '';
      }
      if (form.value.id != null) {
        updateRoute(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getHostRoute();
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addRoute(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getHostRoute();
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除线路编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delRoute(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = '线路导入';
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("basic/route/import/template", {
  }, `route_template_${new Date().getTime()}.xlsx`);
};

/** 文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getHostRoute();
  getList();
};
function httpRequest(data) {
  // 封装FormData对象
  data.data[data.filename] = data.file
  upload.open = false;
  upload.isUploading = false;
  proxy.importFile(upload.url, data.data).then(res => {
    proxy.$refs["uploadRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + res.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
  }).catch(err => {
    proxy.$refs["uploadRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + err + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
  })
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadForm"].validate((valid) => {
    if (valid) {
      proxy.$refs["uploadRef"].submit();
    } else {
      console.log('error submit!!');
      return false;
    }
  });
};

/** 导出按钮操作 */
function handleExport() {
  proxy.download('basic/route/export', {
    ...queryParams.value
  }, `route_${new Date().getTime()}.xlsx`)
}

getHostRoute();

getDeptTree();

getAreaTree();

getList();

const routeId = ref(null)
const deptId = ref(null)
const manageTitle = ref('')
const manageType = ref('')
const manageOpen = ref(false)

//站点管理
import routeStation from './components/routeStation/index'
function routeStationList(row) {
  manageType.value = 'routeStation';
  manageTitle.value = '站点管理';
  manageOpen.value = true;
  routeId.value = row.id;
}
//场区管理
import routeRegion from './components/routeRegion/index'
function routeRegionList(row) {
  manageType.value = 'routeRegion';
  manageTitle.value = '场区管理';
  manageOpen.value = true;
  routeId.value = row.id;
}
//车辆管理
import routeVehicle from './components/routeVehicle/index'
function routeVehicleList(row) {
  manageType.value = 'routeVehicle';
  manageTitle.value = '车辆管理';
  manageOpen.value = true;
  routeId.value = row.id;
  deptId.value = row.deptId;
}
//站点考核配置
import routeConfig from './components/extend/routeStationExtend/index'
function routeStationsConfigList(row) {
  manageType.value = 'routeStationsConfig';
  manageTitle.value = '站点考核配置';
  manageOpen.value = true;
  routeId.value = row.id;
}

//扩展配置
import routeStationExtend from './components/extend/index'
function routeConfigList(row) {
  manageType.value = 'routeConfig';
  manageTitle.value = '扩展配置';
  manageOpen.value = true;
  routeId.value = row.id;
}


//编辑司机每日标准工作时长
import routeManHour from './components/routeManHour/index'
function routeManHourList(row) {
  manageType.value = 'routeManHour';
  manageTitle.value = '编辑司机每日标准工作时长';
  manageOpen.value = true;
  routeId.value = row.id;
}

/** 线路站点导入参数 */
const uploadStation = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  form: {
    type: null,
    areaId: null,
    stationRadius: '0',
    positiveAngle: '0',
    reverseAngle: '0',
    updateScope: '2',
    deptId: undefined
  },
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/basic/routeStation/import/data"
})

/** 线路站点导入按钮操作 */
function handleRouteStationImport() {
  uploadStation.title = '线路站点导入';
  uploadStation.open = true;
}

/** 线路站点下载模板操作 */
function importRouteStationTemplate() {
  proxy.download("basic/routeStation/import/template", {
  }, `route_station_template_${new Date().getTime()}.xlsx`);
};

/** 线路站点文件上传中处理 */
const handleRouteStationFileUploadProgress = (event, file, fileList) => {
  uploadStation.isUploading = true;
};

/** 线路站点文件上传成功处理 */
const handleRouteStationFileSuccess = (response, file, fileList) => {
  uploadStation.open = false;
  uploadStation.isUploading = false;
  proxy.$refs["routeStationRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
};
function httpStationRequest(data) {
  // 封装FormData对象
  data.data[data.filename] = data.file
  uploadStation.open = false;
  uploadStation.isUploading = false;
  proxy.importFile(uploadStation.url, data.data).then(res => {
    proxy.$refs["routeStationRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + res.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
  }).catch(err => {
    proxy.$refs["routeStationRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + err + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
  })
}
/** 线路站点提交上传文件 */
function submitRouteStationFileForm() {
  proxy.$refs["routeStationForm"].validate((valid) => {
    if (valid) {
      proxy.$refs["routeStationRef"].submit();
    } else {
      console.log('error submit!!');
      return false;
    }
  });
};
</script>

<style scoped>
.el-dropdown {
  vertical-align: middle;
}
</style>
